package com.platform.api;

import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.util.DateUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: @author zhurusen <br>
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApiResourceService apiResourceService;
    @Autowired
    private ApiFollowService apiFollowService;
    @Autowired
    private ApiOrderService apiOrderService;
    @Autowired
    private ApiUserVideoService apiUserVideoService;
    @Autowired
    private ApiUserVideoBillService apiUserVideoBillService;
    @Autowired
    private ApiUserLabelService apiUserLabelService;
    @Autowired
    private ApiLabelService apiLabelService;
    @Autowired
    private  ApiCallUserBillService callUserBillService;


    /**
     * 获取个人信息
     */
    @RequestMapping("info")
    public R info(@LoginUser UserVo loginUser) {
        UserInfo userInfo = apiUserService.toUserInfo(loginUser.getId(), loginUser);
        Map<String, Object> params = new HashMap<>();
        params.put("cmUserId", loginUser.getId());
        userInfo.setFollowNum(apiFollowService.queryTotal(params));
        userInfo.setAvailableAmount(loginUser.getAvailable_amount());
        callUserBillService.updateCallList(loginUser);

        //累计收益
        return R.ok(0, "个人信息", userInfo);
    }

    /**
     * 获取主播当前状态
     */
    @RequestMapping("onlineStatus")
    public R onlineStatus(@LoginUser UserVo loginUser, Long userId) {

        UserVo userVo = apiUserService.queryObject(userId);

        return R.ok(0, "个人信息", userVo.getOnline_status());
    }

    /**
     * 获取主播当前状态
     */
    @RequestMapping("onlineStatusV2")
    public R onlineStatusV2(@LoginUser UserVo loginUser, Long userId) {

        UserVo userVo = apiUserService.queryObject(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("onlineStatus", userVo.getOnline_status());
        map.put("livePrice", userVo.getLive_price());

        return R.ok(0, "个人信息", map);
    }

    @RequestMapping("isFollow")
    public R isFollow(@LoginUser UserVo loginUser, Long id) {
        if (loginUser != null) {
            Map<String, Object> params = new HashMap<>();
            params.put("cmUserId", loginUser.getId());
            params.put("zbUserId", id);
            List<ApiFollowVo> followVos = apiFollowService.queryList(params);
            if (followVos.size() > 0) {
                return R.ok(0, "已关注", "1");
            }
        }
        return R.ok(0, "未关注", "2");
    }

    /**
     * 获取主播详情
     *
     * @param loginUser
     * @param userId
     * @return
     */
    @RequestMapping("infoByUserId")
    public R infoByZbUserId(@LoginUser UserVo loginUser, Long userId) {
        Map<String, Object> reMap = new HashMap<>();

        UserInfo userInfo = apiUserService.toUserInfo(userId, loginUser);
        Map<String, Object> paramsFollow = new HashMap<>();
        if (loginUser != null) {
            paramsFollow.put("zbUserId", userId);
        }

        userInfo.setFollowNum(apiFollowService.queryTotal(paramsFollow));

        reMap.put("userInfo", userInfo);

        Map<String, Object> params = new HashMap<>();
        params.put("zbUserId", userId);
        userInfo.setFollowNum(apiFollowService.queryTotal(params));

        List<UserServiceVo> serviceVos = new ArrayList<>();

        if (userInfo.getWake() == 1) {
            UserServiceVo info = new UserServiceVo();
            info.setMouldId(3L);
            info.setMouldName("叫醒服务");
            info.setVoiceUrl(userInfo.getVoiceUrl());
            info.setPrice(userInfo.getEmotionPrice());
            if (loginUser != null) {
                params = new HashMap<>();
                params.put("zbUserId", userId);
                params.put("mouldId", 3);
                info.setCount(apiOrderService.selectCount(params));
            }

            Map<String, Object> labelparams = new HashMap();
            labelparams.put("page", 1);
            labelparams.put("limit", 3);
            labelparams.put("zbUserId", userId);
            labelparams.put("mould_name", "wake");
            List<Map<String, Object>> labellist = apiUserLabelService.selectMap(labelparams);


            List<ApiLabelVo> lableList = new ArrayList<>();

            for (Map<String, Object> map : labellist) {
                Map<String, Object> param = new HashMap();
                param.put("name", map.get("name"));
                List<ApiLabelVo> labelVos = apiLabelService.queryList(param);
                if (labelVos != null && labelVos.size() > 0) {
                    lableList.add(labelVos.get(0));
                }
            }

            info.setLableList(lableList);
            serviceVos.add(info);
        }
        if (userInfo.getEmotion() == 1) {
            UserServiceVo info = new UserServiceVo();
            info.setMouldId(2L);
            info.setMouldName("情感咨询");
            info.setVoiceUrl(userInfo.getVoiceUrl());
            info.setPrice(userInfo.getWakePrice());

            if (loginUser != null) {
                params = new HashMap<>();
                params.put("zbUserId", userId);
                params.put("mouldId", 2);
            }


            info.setCount(apiOrderService.selectCount(params));


            Map<String, Object> labelparams = new HashMap();
            labelparams.put("page", 1);
            labelparams.put("limit", 3);
            labelparams.put("zbUserId", userId);
            labelparams.put("mould_name", "emotion");
            List<Map<String, Object>> labellist = apiUserLabelService.selectMap(labelparams);

            List<ApiLabelVo> lableList = new ArrayList<>();

            for (Map<String, Object> map : labellist) {
                Map<String, Object> param = new HashMap();
                param.put("name", map.get("name"));
                List<ApiLabelVo> labelVos = apiLabelService.queryList(param);
                if (labelVos != null && labelVos.size() > 0) {
                    lableList.add(labelVos.get(0));
                }
            }

            info.setLableList(lableList);

            serviceVos.add(info);
        }
        if (userInfo.getGuide() == 1) {
            UserServiceVo info = new UserServiceVo();
            info.setMouldId(4L);
            info.setMouldName("旅游向导");
            info.setVoiceUrl(userInfo.getVoiceUrl());
            info.setPrice(userInfo.getGuidePrice());

            if (loginUser != null) {
                params = new HashMap<>();
                params.put("zbUserId", userId);
                params.put("mouldId", 4);
                info.setCount(apiOrderService.selectCount(params));
            }


            Map<String, Object> labelparams = new HashMap();
            labelparams.put("page", 1);
            labelparams.put("limit", 3);
            labelparams.put("zbUserId", userId);
            labelparams.put("mould_name", "guide");
            List<Map<String, Object>> labellist = apiUserLabelService.selectMap(labelparams);


            List<ApiLabelVo> lableList = new ArrayList<>();

            for (Map<String, Object> map : labellist) {
                Map<String, Object> param = new HashMap();

                param.put("name", map.get("name"));

                List<ApiLabelVo> labelVos = apiLabelService.queryList(param);
                if (labelVos != null && labelVos.size() > 0) {
                    lableList.add(labelVos.get(0));
                }
            }

            info.setLableList(lableList);
            serviceVos.add(info);
        }
        reMap.put("serviceVo", serviceVos);

        return R.ok(0, "主播基本信息", reMap);
    }


    /**
     * 更新个人信息
     *
     * @param loginUser
     * @param avatar
     * @param nickName
     * @param birth     yyyy-MM
     * @return
     */
    @RequestMapping("saveAvatar")
    public R saveAvatar(@LoginUser UserVo loginUser, String avatar, String nickName, String birth, Integer gender) {
        try {
            Integer age = 26;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");

            if (avatar != null && !avatar.isEmpty()) {
                loginUser.setAvatar(avatar);
            }
            if (nickName != null && !nickName.isEmpty()) {
                loginUser.setNickname(nickName);
            }
            if (birth != null && !birth.isEmpty()) {
                loginUser.setBirthday(df.parse(birth));
                age = DateUtils.getAge(df.parse(birth));
                loginUser.setAge(age);
            }
            if (gender != null) {
                loginUser.setGender(gender);
            }

            //计算年龄
            apiUserService.update(loginUser);

            return R.ok(0, "更新成功", age);
        } catch (Exception e) {
            e.printStackTrace();
            return R.ok(12, "系统偷懒了", "");
        }

    }

    /**
     * 叫醒服务
     *
     * @param loginUser
     * @param wake      叫醒1 开通 2 未开通
     * @param wakePrice 单价
     * @return
     */
    @RequestMapping("wake")
    public R wake(@LoginUser UserVo loginUser, Integer wake, BigDecimal wakePrice) {
        loginUser.setWake(wake);
        loginUser.setWake_price(wakePrice);
        apiUserService.update(loginUser);
        return R.ok(0, "更新成功", "");
    }

    /**
     * 情感服务
     *
     * @param loginUser
     * @param emotion      叫醒1 开通 2 未开通
     * @param emotionPrice 单价
     * @return
     */
    @RequestMapping("emotion")
    public R emotion(@LoginUser UserVo loginUser, Integer emotion, BigDecimal emotionPrice) {
        loginUser.setEmotion(emotion);
        loginUser.setEmotion_price(emotionPrice);
        apiUserService.update(loginUser);
        return R.ok(0, "更新成功", "");
    }

    /**
     * 向导服务
     *
     * @param loginUser
     * @param guide      叫醒1 开通 2 未开通
     * @param guidePrice 单价
     * @return
     */
    @RequestMapping("guide")
    public R guide(@LoginUser UserVo loginUser, Integer guide, BigDecimal guidePrice) {
        loginUser.setGuide(guide);
        loginUser.setGuide_price(guidePrice);
        apiUserService.update(loginUser);
        return R.ok(0, "更新成功", "");
    }


    /**
     * 主播认证
     *
     * @param loginUser
     * @param nickName      昵称
     * @param mobile        手机号
     * @param height        身高
     * @param weight        体重
     * @param constellation 星座
     * @param cityName      所在城市infoByUserId
     * @param introduction  个人资料
     * @return
     */
    @RequestMapping("authentication")
    public R authentication(@LoginUser UserVo loginUser, String picIds, String nickName, String mobile, BigDecimal height, BigDecimal weight, String constellation, String cityName, String introduction,
                            BigDecimal livePrice, String labelIds) {

        loginUser.setNickname(nickName);
        loginUser.setMobile(mobile);
        loginUser.setHeight(height);
        loginUser.setWeight(weight);
        loginUser.setLive(1);
        loginUser.setConstellation(constellation);
        loginUser.setCity_name(cityName);
        loginUser.setIntroduction(introduction);

        if (loginUser.getApplication_status() != 3) {
            loginUser.setApplication_status(2);
        }

        loginUser.setLive_price(livePrice);
        apiUserService.update(loginUser);

        Map<String, Object> params = new HashMap<>();
        params.put("mouldId", loginUser.getId());
        params.put("mouldName", "userVo");
        List<ApiResourceVo> apiResourceVos = apiResourceService.selectList(params);
        for (ApiResourceVo info : apiResourceVos) {
            if (picIds.indexOf(info.getId().toString()) == -1) {
                apiResourceService.del(info.getId());
            }
        }

        apiResourceService.updataByUserVo(picIds, loginUser.getId(), "userVo", 1);

        /**
         * 解析标签1-删除之前的标签
         */
        Map<String, Object> params_label = new HashMap<>();
        params_label.put("mouldId", loginUser.getId());
        params_label.put("mould_name", "userVo");
        List<ApiUserLabelVo> labelVos = apiUserLabelService.selectList(params_label);

        for (ApiUserLabelVo info : labelVos) {
            apiUserLabelService.del(info.getId());
        }


        /**
         * 解析标签2
         */
        if (labelIds != null) {
            String labelArr[] = labelIds.split(",");
            for (int i = 0; i < labelArr.length; i++) {
                if (!labelArr[i].trim().equals("")) {
                    ApiLabelVo apiLabelVo = apiLabelService.selectOne(Long.valueOf(labelArr[i]));
                    ApiUserLabelVo apiUserLabelVo = new ApiUserLabelVo();
                    apiUserLabelVo.setLabelId(apiLabelVo.getId());
                    apiUserLabelVo.setLabelName(apiLabelVo.getName());
                    apiUserLabelVo.setUserId(loginUser.getId());
                    apiUserLabelVo.setTvAnchor(loginUser.getId());
                    apiUserLabelVo.setMouldId(loginUser.getId());
                    apiUserLabelVo.setMouldName("userVo");

                    apiUserLabelService.save(apiUserLabelVo);
                }
            }
        }


        return R.ok(0, "提交成功", "");
    }


    /**
     * 我是窝主 有多少预约量
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("appointment")
    public R appointment(@LoginUser UserVo loginUser) {
        Map<String, Object> params = new HashMap<>();
        params.put("zbUserId", loginUser.getId());
        params.put("status", 1);
        Integer count = apiOrderService.selectCount(params);
        return R.ok(0, "提交成功", count);
    }


    /**
     * 我是窝主 语音
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("voice")
    public R voice(@LoginUser UserVo loginUser, String voiceUrl) {
        loginUser.setVoice_url(voiceUrl);
        apiUserService.update(loginUser);
        return R.ok(0, "提交成功", "");
    }

    /**
     * 切换状态 1在线  2在聊 3勿扰 4离线
     *
     * @param loginUser
     * @param onlineStatus
     * @return
     */
    @RequestMapping("changeStatus")
    public R changeStatus(@LoginUser UserVo loginUser, Integer onlineStatus) {
        loginUser.setOnline_status(onlineStatus);
        apiUserService.update(loginUser);
        return R.ok(0, "提交成功", "");
    }

    /**
     * 我喜欢的
     *
     * @param loginUser
     * @param type      1 我喜欢的  2 我购买的
     * @param page
     * @return
     */
    @RequestMapping("list")
    public R list(@LoginUser UserVo loginUser, Long userId, @RequestParam(value = "type", defaultValue = "1") Integer type, @RequestParam(value = "page", defaultValue = "1") Integer page) {
        Map<String, Object> params = new HashMap();
        params.put("userId", userId);
        if (type == 1) {
            params.put("like", 1);
        }
        if (type == 2) {
            params.put("payStatus", 1);
        }
        params.put("page", page);
        params.put("limit", 10);

        params.put("sidx", "id");
        params.put("order", "desc");

        Query query = new Query(params);


        List<ApiUserVideoVo> list = apiUserVideoService.selectList(query);
        for (ApiUserVideoVo info : list) {

            info.setUserVo(apiUserService.toUserInfo(info.getUserId(), loginUser));

            Map<String, Object> paramBill = new HashMap();
            paramBill.put("userVideoId", info.getId());
            paramBill.put("userId", loginUser.getId());
            paramBill.put("sidx", "id");
            paramBill.put("order", "desc");

            Query queryBill = new Query(paramBill);

            List<ApiUserVideoBillVo> billVos = apiUserVideoBillService.selectList(queryBill);

            if (billVos.size() > 0) {
                ApiUserVideoBillVo apiUserVideoBillVo = billVos.get(0);
                if (apiUserVideoBillVo.getLike() == 1) {
                    info.setIsLike(1);
                }
                if (apiUserVideoBillVo.getReward() == 1) {
                    info.setPayStatus(2);
                }
            }
        }

        return R.ok(0, "请求成功", list);
    }


}